import { Controller, Inject, Post, Get, Body, Query } from '@midwayjs/core'
import { UserService } from '../../service/app/UserService'
import { UserChildService } from '../../service/app/UserChildService'
import { DonateService } from '../../service/app/DonateService'
import { RescueInfoService } from '../../service/app/RescueInfoService'
import { BaseController } from '../base.chontroller'

@Controller('/app/user')
export class UserController extends BaseController {
  @Inject()
  service!: UserService

  @Inject()
  userChildService!: UserChildService

  @Inject()
  donateService!: DonateService

  @Inject()
  rescueInfoService!: RescueInfoService

  // 修改用户信息
  @Post('/update-profile')
  async updateProfile(@Body() data: {
    userId: string
    nickname?: string
    email?: string
    signature?: string
    password?: string
    avatar?: string
  }) {
    if (!data?.userId) {
      return this.fail('缺少必要参数：userId')
    }

    try {
      await this.service.updateProfile(data.userId, {
        nickname: data.nickname,
        email: data.email,
        signature: data.signature,
        password: data.password,
        avatar: data.avatar
      })
      return this.success(null, '修改成功')
    } catch (err: any) {
      return this.fail(err.message || '修改失败')
    }
  }

  // 获取用户信息
  @Get('/info')
  async getUserInfo(@Query('userId') userId: string) {
    if (!userId) {
      return this.fail('缺少必要参数：userId')
    }

    try {
      const result = await this.service.getUserInfo(userId)
      return this.success(result, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取用户信息失败')
    }
  }

  // 根据用户ID获取关联的儿童信息
  @Get('/children')
  async getUserChildren(@Query('userId') userId: string) {
    if (!userId) {
      return this.fail('缺少必要参数：userId')
    }

    try {
      const result = await this.userChildService.getChildrenByUserId(userId)
      return this.success<IList<typeof result.items[0]>>(result)
    } catch (err: any) {
      return this.fail(err.message || '获取关联儿童信息失败')
    }
  }

  // 添加用户儿童关联
  @Post('/add-child')
  async addUserChild(@Body() data: {
    userId: string
    childId: number
    relationType?: number
  }) {
    if (!data?.userId || !data?.childId) {
      return this.fail('缺少必要参数：userId、childId')
    }

    try {
      const result = await this.userChildService.addUserChildRelation(data)
      return this.success(result, '添加关联成功')
    } catch (err: any) {
      return this.fail(err.message || '添加关联失败')
    }
  }

  // 删除用户儿童关联
  @Post('/remove-child')
  async removeUserChild(@Body() data: {
    userId: string
    childId: number
  }) {
    if (!data?.userId || !data?.childId) {
      return this.fail('缺少必要参数：userId、childId')
    }

    try {
      await this.userChildService.removeUserChildRelation(data.userId, data.childId)
      return this.success(null, '删除关联成功')
    } catch (err: any) {
      return this.fail(err.message || '删除关联失败')
    }
  }

  // 创建新儿童
  @Post('/create-child')
  async createChild(@Body() data: {
    name: string
    phone: string
    homeAddress?: string
    birthday?: string
    headImg?: string
    guardian?: string
    gender?: number
    userId?: string
  }) {
    if (!data?.name || !data?.phone) {
      return this.fail('缺少必要参数：name、phone')
    }

    try {
      const result = await this.userChildService.createChild({
        name: data.name,
        phone: data.phone,
        homeAddress: data.homeAddress,
        birthday: data.birthday,
        headImg: data.headImg,
        guardian: data.guardian,
        gender: data.gender,
        userId: data.userId
      })
      return this.success(result, '创建成功')
    } catch (err: any) {
      return this.fail(err.message || '创建儿童失败')
    }
  }

  // 根据儿童ID获取儿童详情
  @Get('/child-detail')
  async getChildDetail(@Query('childId') childId: string) {
    if (!childId) {
      return this.fail('缺少必要参数：childId')
    }

    try {
      const result = await this.userChildService.getChildDetail(parseInt(childId))
      return this.success(result, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取儿童详情失败')
    }
  }

  // 根据儿童ID编辑儿童信息
  @Post('/update-child')
  async updateChild(@Body() data: {
    childId: number
    name?: string
    phone?: string
    homeAddress?: string
    birthday?: string
    headImg?: string
    guardian?: string
    gender?: number
  }) {
    if (!data?.childId) {
      return this.fail('缺少必要参数：childId')
    }

    try {
      const result = await this.userChildService.updateChild(data.childId, {
        name: data.name,
        phone: data.phone,
        homeAddress: data.homeAddress,
        birthday: data.birthday,
        headImg: data.headImg,
        guardian: data.guardian,
        gender: data.gender
      })
      return this.success(result, '更新成功')
    } catch (err: any) {
      return this.fail(err.message || '更新儿童信息失败')
    }
  }

  // 获取用户参与状态（是否捐赠过、是否帮扶过）
  @Get('/participation-status')
  async getUserParticipationStatus(@Query('userId') userId?: string) {
    if (!userId) {
      return this.fail('缺少必要参数：userId')
    }

    try {
      const userIdNum = parseInt(userId)
      const [donateResult, rescueResult] = await Promise.all([
        this.donateService.checkUserHasDonated(userIdNum),
        this.rescueInfoService.checkUserHasRescued(userIdNum)
      ])

      return this.success({
        hasDonated: donateResult.hasDonated,
        lastDonateTime: donateResult.lastDonateTime,
        hasRescued: rescueResult.hasRescued,
        lastRescueTime: rescueResult.lastRescueTime
      }, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取用户参与状态失败')
    }
  }

  // 获取用户证书列表
  @Get('/certificates')
  async getUserCertificates(@Query('userId') userId: string) {
    if (!userId) {
      return this.fail('缺少必要参数：userId')
    }

    try {
      const certificates = await this.service.getUserCertificates(userId)
      return this.success(certificates, '获取成功')
    } catch (err: any) {
      return this.fail(err.message || '获取用户证书失败')
    }
  }
}